<?php

namespace yunj\app\admin\enum\route;

use yunj\app\admin\enum\Enum;
use yunj\app\admin\model\AdminRoute;
use yunj\app\admin\model\AdminRouteGroup;
use yunj\app\admin\model\AdminRouteRequest;
use yunj\app\admin\model\Model;

/**
 * 路由请求项配置类型
 * Class RoutePageFormType
 * @package yunj\app\admin\enum
 */
final class RouteDataType extends Enum {

    const GROUP = 'group';

    const ROUTE = 'route';

    const REQUEST = 'request';

    /**
     * 所有枚举的属性值
     * @return array
     */
    public static function allEnumAttrs(): array {
        return [
            self::GROUP => [
                'title' => '分组',
                'model' => AdminRouteGroup::class,
                'parent_model' => AdminRouteGroup::class,
                'table_unique_key' => ['system_key'],
                'table_pid_key' => 'pid',
            ],
            self::ROUTE => [
                'title' => '路由',
                'model' => AdminRoute::class,
                'parent_model' => AdminRouteGroup::class,
                'table_unique_key' => ['system_key', 'name'],
                'table_pid_key' => 'group_id',
            ],
            self::REQUEST => [
                'title' => '请求项',
                'model' => AdminRouteRequest::class,
                'parent_model' => AdminRoute::class,
                'table_unique_key' => ['system_key'],
                'table_pid_key' => 'route_id',
            ],
        ];
    }

    /**
     * 获取模型实例
     * @return Model|null|mixed
     */
    public function getModel() {
        $model = $this->getAttr('model');
        return $model ? app($model) : null;
    }

    /**
     * 获取父模型实例
     * @return Model|null|mixed
     */
    public function getParentModel() {
        $model = $this->getAttr('parent_model');
        return $model ? app($model) : null;
    }

    /**
     * 获取对应数据表唯一性索引
     * @return array
     */
    public function getTableUniqueKey(): array {
        $key = $this->getAttr('table_unique_key');
        if (!$key) {
            return [];
        }
        return is_array($key) ? $key : [$key];
    }

    /**
     * 获取对应数据表pid
     * @return string
     */
    public function getTablePidKey(): string {
        $key = $this->getAttr('table_pid_key');
        return $key ?: 'pid';
    }

}